package com.everflourish.yeah100.http;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.entity.statistics.ClassSimple;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.constant.PaperType;
import com.everflourish.yeah100.utils.constant.RoleEnum;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 考试信息接口封装
 *
 * @author pf
 * @date 2015-1-14
 */
public class ExaminationRequest extends BaseRequest {
    private static ExaminationRequest mRequest;

    private ExaminationRequest() {
    }

    public static ExaminationRequest getInstance() {
        if (mRequest == null) {
            mRequest = new ExaminationRequest();
        }
        return mRequest;
    }

    /**
     * 获取考试列表信息
     *
     * @param roleEnum             角色
     * @param startIndex           开始位置
     * @param selectedCount        获取数量(默认10条)
     * @param examinationName      考试名称（支持模糊查询）
     * @param subject              科目名称
     * @param dateFrom             查询的开始时间
     * @param dateTo               查询的结束时间
     * @param includeDeletedRecord 是否包含已删除的考试信息
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest examinationListRequest(RoleEnum roleEnum,
                                                    Integer startIndex, Integer selectedCount, String examinationName,
                                                    String subject, String dateFrom, String dateTo,
                                                    Boolean includeDeletedRecord, String friendId,
                                                    Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = null;

        Map<String, Object> map = new HashMap<String, Object>();
        if (startIndex != null) {
            map.put("startIndex", startIndex);
        }
        if (selectedCount != null) {
            map.put("selectedCount", selectedCount);
        }
        if (examinationName != null) {
            map.put("examinationName", examinationName);
        }
        if (subject != null) {
            map.put("subject", subject);
        }
        if (dateFrom != null) {
            map.put("dateFrom", dateFrom);
        }
        if (dateTo != null) {
            map.put("dateTo", dateTo);
        }
        if (friendId == null && includeDeletedRecord != null
                && Yeah100.mRoleEnum == RoleEnum.TEACHER) {
            map.put("includeDeletedRecord", includeDeletedRecord ? 1 : 0);
        }
        if (friendId != null) {
            map.put("friendId", friendId);
        }
        JSONObject jsonObject = new JSONObject(map);
        String url = null;
        if (friendId != null) {
            url = URL_EXAMINATION_HISTORY_FRIEND;
        } else if (roleEnum == RoleEnum.TEACHER) { // 获取老师的请求信息
            url = URL_EXAMINATION_HISTORY_TEACHER;
        } else { // 获取学生的请求信息
            url = URL_EXAMINATION_HISTORY_STUDENT;
        }
        request = new JsonObjectRequest(Method.POST, url, jsonObject, listener,
                errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }


    /**
     * 统计学生成绩请求
     *
     * @param examinationId 考试id
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest executeStatisticJob(String examinationId,
                                                 Listener<JSONObject> listener, ErrorListener errorListener) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("examinationId", examinationId);
        JSONObject jsonObject = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                URL_STATISTIC_JOB, jsonObject, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS * 5,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 老师-统计分析-成绩表请求
     *
     * @param examinationId 考试的id
     * @param classSimples  考试的班级
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest tScoreListRequest(String examinationId,
                                               List<ClassSimple> classSimples, Listener<JSONObject> listener,
                                               ErrorListener errorListener) {
        JsonObjectRequest request = null;

        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("examinationId", examinationId);
            JSONObject jsonObject = new JSONObject(map);
            if (classSimples != null) {
                List<String> listMap = new ArrayList<String>();
                for (ClassSimple c : classSimples) {
                    listMap.add(c.getId());
                }
                JSONArray idsJsonArray = new JSONArray(listMap);
                jsonObject.put("classIds", idsJsonArray);
            }
            System.out.println(jsonObject.toString());
            request = new JsonObjectRequest(Method.POST,
                    URL_EXAMINATION_SCORE_STATISTIC, jsonObject, listener,
                    errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return request;
    }

    /**
     * 老师-统计分析-客观题错误率请求
     *
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest tFailureRateObjectRequest(String examinationId,
                                                       List<ClassSimple> classSimples, PaperType paperType,
                                                       Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = null;
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("examinationId", examinationId);
            map.put("paperType", paperType.text);
            JSONObject jsonObject = new JSONObject(map);
            if (classSimples != null) {
                List<String> listMap = new ArrayList<String>();
                for (ClassSimple c : classSimples) {
                    listMap.add(c.getId());
                }
                JSONArray idsJsonArray = new JSONArray(listMap);
                jsonObject.put("classIds", idsJsonArray);
            }
            System.out.println(jsonObject.toString());
            request = new JsonObjectRequest(Method.POST,
                    URL_EXAMINATION_FAILURERATE_OBJECT, jsonObject, listener,
                    errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return request;
    }

    /**
     * 老师-统计分析-班级统计请求
     *
     * @param examinationId 考试的id
     * @param classSimples  考试的班级
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest tClassStatisticsRequest(String examinationId,
                                                     List<ClassSimple> classSimples, Listener<JSONObject> listener,
                                                     ErrorListener errorListener) {
        JsonObjectRequest request = null;
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("examinationId", examinationId);
            JSONObject jsonObject = new JSONObject(map);
            if (classSimples != null) {
                List<String> listMap = new ArrayList<String>();
                for (ClassSimple c : classSimples) {
                    listMap.add(c.getId());
                }
                JSONArray idsJsonArray = new JSONArray(listMap);
                jsonObject.put("classIds", idsJsonArray);
            }
            request = new JsonObjectRequest(Method.POST,
                    URL_EXAMINATION_CLASS_STATISTIC, jsonObject, listener,
                    errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return request;
    }

    /**
     * 删除考试信息请求
     *
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest deleteExaminationRequest(String examinationId,
                                                      Listener<JSONObject> listener, ErrorListener errorListener) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("examinationId", examinationId);
        JSONObject jsonObject = new JSONObject(map);

        String url = "";
        if (Yeah100.mRoleEnum == RoleEnum.TEACHER) {
            url = URL_EXAMINATION_TEACHER_DELETE;
        } else {
            url = URL_EXAMINATION_STUDENT_DELETE;
        }
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, url,
                jsonObject, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        return request;
    }

    /**
     * 发布考试信息请求
     *
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest publishExaminationRequest(String examinationId,
                                                       Listener<JSONObject> listener, ErrorListener errorListener) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("examinationId", examinationId);
        JSONObject jsonObject = new JSONObject(map);
        String url = URL_EXAMINATION_TEACHER_PUBLISH + "/" + examinationId;
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, url,
                jsonObject, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 获取考试内容状态
     *
     * @param examinationId
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest checkExaminationStatus(String examinationId,
                                                    Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_EXAMINATION_CHECK_STATUS + "/" + examinationId, null,
                listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        return request;
    }

    /**
     * 导出报表请求
     *
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest exportExaminationRequest(String examinationId,
                                                      String email, Listener<JSONObject> listener,
                                                      ErrorListener errorListener) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("examinationId", examinationId);
        map.put("email", email);
        JSONObject jsonObject = new JSONObject(map);
        String url = URL_EXAMINATION_TEACHER_EXPORT;
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, url,
                jsonObject, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

}
